package cn.jinbyte.web.filter;


import cn.jinbyte.web.config.XssProperties;
import cn.jinbyte.web.utils.PathMatcherUtil;
import cn.jinbyte.web.wrapper.XssRequestWrapper;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.util.ContentCachingRequestWrapper;

import java.io.IOException;

/**
 * XSS防护过滤器，基于配置文件参数进行过滤
 */
public class XssFilter implements Filter {

    private final XssProperties xssProperties;

    public XssFilter(XssProperties xssProperties) {
        this.xssProperties = xssProperties;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        // 如果XSS防护未启用，直接放行
        if (!xssProperties.isEnabled()) {
            chain.doFilter(request, response);
            return;
        }

        // 检查是否为排除路径
        if (PathMatcherUtil.isExcluded(httpRequest, xssProperties.getExcludePaths())) {
            chain.doFilter(request, response);
            return;
        }

        // 使用XSS请求包装器处理请求
        ContentCachingRequestWrapper cachingRequest = new ContentCachingRequestWrapper(httpRequest);
        XssRequestWrapper xssRequest = new XssRequestWrapper(cachingRequest);

        chain.doFilter(xssRequest, response);
    }
}
